<template>
  <div class="app-container">
    <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { importEmployeeApi } from '@/api/employees'
import moment from 'moment'
export default {
  name: 'Import',
  data() {
    return {}
  },
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: '上传少于1M的文件',
        type: 'warning'
      })
      return false
    },
    // 上传成功
    async handleSuccess({ results, header }) {
      // console.log(results) // 数据
      // console.log(header) // 表头
      if (this.type === 'user') {
        const userRelations = {
          入职日期: 'timeOfEntry',
          手机号: 'mobile',
          姓名: 'username',
          转正日期: 'correctionTime',
          工号: 'workNumber'
        }
        const res = results.map(item => {
          const obj = {}
          for (const key in item) {
            // console.log(key) 键名
            // console.log(userRelations[key]) 键值
            // console.log(item[key]) 键值
            if (
              userRelations[key] === 'correctionTime' ||
              userRelations[key] === 'timeOfEntry'
            ) {
              obj[userRelations[key]] = moment(
                this.formatExcelDate(item[key], '-')
              )
                .add(1, 'days')
                .format('YYYY-MM-D')
              // moment(date).add(1, ‘days’).format(‘YYYY-MM-DD’)
            } else {
              // console.log(obj[userRelations[key]]) // undefined
              // console.log(userRelations[key]) // mobile
              // console.log(item[key]) // 751786621
              obj[userRelations[key]] = item[key] // obj新增键值对,左边是新增属性，右边是赋值
            }
          }
          return obj // return 出去要接收
        })
        const {
          data: { message }
        } = await importEmployeeApi(res)
        this.$message.success(message)
        this.$router.back()
      }
      if (this.type === 'attend') {
        // 考勤的上传
        console.log('考勤上传')
      }
    },
    formatExcelDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return (
          year +
          format +
          (month < 10 ? '0' + month : month) +
          format +
          (date < 10 ? '0' + date : date)
        )
      }
      return (
        year +
        (month < 10 ? '0' + month : month) +
        (date < 10 ? '0' + date : date)
      )
    }
  }
}
</script>
